let oneRun = true;
import Vue from "vue";
import VueRouter from "vue-router";
import defalutRouter from "_my/router/config/defaultRouter";
import { initRouter } from "_my_utils/router";
import Nprogress from "nprogress";
import "nprogress/nprogress.css";
import { MessageBox } from "element-ui";
Vue.use(VueRouter);
const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function push(location, onResolve, onReject) {
  if (onResolve || onReject)
    return originalPush.call(this, location, onResolve, onReject);
  return originalPush.call(this, location).catch((err) => err);
};
const routes = defalutRouter;
const router = new VueRouter({
  routes,
});
const sourceWarn = window.console.warn;
window.console.warn = function (...rest) {
  const args = Array.from(rest);
  if (
    args[0] &&
    args[0].includes("Route with name") &&
    args[0].includes("does not exist")
  ) {
    setTimeout(() => {
      router.push("/404");
    }, 0);
  }
  sourceWarn(...rest);
};
router.beforeEach((to, from, next) => {
  if (to.name === "403") {
    MessageBox.alert(
      `<div style='display:flex' > <span style='font-size:24px;color:red;margin-right:10px' class='el-icon-warning-outline'></span><span>前端未创建该路由文件，请前联系前端程序员创建前端路由页面！</span></div>`,
      "提示",
      {
        dangerouslyUseHTMLString: true,
        confirmButtonText: "确定",
        callback: () => {
          next({ name: "home" });
        },
      }
    );
    return;
  }
  const token = sessionStorage.getItem("token");
  if (to.meta.title) {
    document.title = "淘个够后台管理 - " + to.meta.title;
  }
  Nprogress.start();
  if (to.name !== "login" && !token) {
    next({ name: "login" });
  } else if (token && oneRun && to.name === null) {
    oneRun = false;
    initRouter();
    next({ ...to, replace: true });
  } else {
    next();
  }
});
router.afterEach(() => {
  Nprogress.done();
});
export default router;
